package com.bugsnag.ohos;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class DateUtils {
    private static final ThreadLocal<DateFormat> ISO_8601_HOLDER = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            TimeZone tz = TimeZone.getTimeZone("UTC");
            DateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
            iso8601.setTimeZone(tz);
            return iso8601;
        }
    };

    private DateUtils() {
    }

    /**
     * toIso8601
     *
     * @param date
     * @return Iso8601
     * @throws IllegalStateException
     */
    public static String toIso8601(Date date) throws IllegalStateException {
        DateFormat dateFormat = ISO_8601_HOLDER.get();
        if (dateFormat == null) {
            throw new IllegalStateException("Unable to find valid dateformatter");
        }
        return dateFormat.format(date);
    }

    /**
     * fromIso8601
     *
     * @param date
     * @return date
     * @throws IllegalArgumentException
     */
    public static Date fromIso8601(String date) throws IllegalArgumentException {
        try {
            return ISO_8601_HOLDER.get().parse(date);
        } catch (ParseException exc) {
            throw new IllegalArgumentException("Failed to parse timestamp", exc);
        }
    }
}
